import { defineEventHandler, readBody, createError, setCookie } from "h3"
import { UserService } from "../../services/userService"
import { saveToken } from "../../utils/jwt"
import { UserRegisterSchema } from '@/schema/user.schema'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const result = UserRegisterSchema().safeParse(body)
  if (!result.success) {
    // 校验失败，返回错误信息
    throw createError({
      statusCode: 400,
      statusMessage: result.error.name,
      data: result.error.issues,
    })
  }
  const { email, password, name } = body

  // 检查用户是否已存在
  const existingUser = await UserService.findByEmail(email);
  if (existingUser) {
    throw createError({
      statusCode: 409,
      statusMessage: "register.user.exist",
    });
  }

  const user = await UserService.createUser({ email, password, name });
  saveToken(event, user)

  return {}
})